﻿@page "/pages/authentication/forgot-password"
@using CleanArchitecture.Blazor.Domain.Identity
@using Microsoft.AspNetCore.WebUtilities
@using System.Text
@using CleanArchitecture.Blazor.Application.Features.Identity.Notifications.ResetPassword
@using System.ComponentModel.DataAnnotations

@inject IStringLocalizer<Forgot> L
@inject ILogger<Forgot> Logger
@inject IdentityRedirectManager RedirectManager
@inject UserManager<ApplicationUser> UserManager
<PageTitle>@Title</PageTitle>

<EditForm Model="Input" FormName="forgot-password" OnValidSubmit="OnValidSubmitAsync" method="post">
    <DataAnnotationsValidator/>

    <MudText Typo="Typo.h4" GutterBottom="true">@L["Forgot Password?"]</MudText>
    <MudText Typo="Typo.body1">@L["No worries! Just enter your email address below and we'll send you a link to reset your password."]</MudText>
    <StatusMessage Message="@Message" Error="true"/>
    <div class="mud-input-control mud-input-outlined-with-label my-4">
        <div class="mud-input-control-input-container">
            <!--!--><!--!-->
            <div class="mud-input mud-input-outlined mud-shrink">
                <InputText @bind-Value="Input.Email" class="mud-input-slot mud-input-root mud-input-root-outlined" type="text" autocomplete="email" aria-required="true" placeholder="name@example.com"/>
                <div class="mud-input-slot mud-input-root mud-input-root-outlined" style="display:none"></div>
                <!--!-->
                <fieldset class="mud-input-outlined-border"><legend>@L["E-mail"]</legend></fieldset>
            </div>
            <!--!-->
            <label class="mud-input-label mud-input-label-animated mud-input-label-outlined mud-input-label-inputcontrol" for="userName">@L["E-mail"]</label>
        </div>
        <div class="mud-input-helper-text mud-input-error">
            <div class="d-flex">
                <ValidationMessage For="() => Input.Email" class="mud-input-error"/>
            </div>
        </div>
    </div>
    <MudButton Variant="Variant.Filled"
               Color="Color.Primary"
               Size="Size.Large"
               ButtonType="ButtonType.Submit"
               FullWidth="true"
               Class="mt-3">
        <MudText>@L["Send E-mail"]</MudText>
    </MudButton>
</EditForm>

@code {
    public const string PageUrl = "/pages/authentication/forgot-password";
    public string Title = "Forgot Password";

    [SupplyParameterFromForm] private InputModel Input { get; set; } = new();
    private readonly string _resetPasswordToken = string.Empty;
    private string _inputToken = string.Empty;
    private string? Message;

    protected override Task OnInitializedAsync()
    {
        Title = L["Forgot Password"];

        return base.OnInitializedAsync();
    }

    private async Task OnValidSubmitAsync()
    {
        var user = await UserManager.FindByEmailAsync(Input.Email);
        if (user is null)
        {
            Message = L["No user found with the provided email address."];
            return;
        }

        if (!await UserManager.IsEmailConfirmedAsync(user))
        {
            Message = L["Your email address has not been confirmed. Please check your inbox for a confirmation email or request a new confirmation link."];
            return;
        }

        var code = await UserManager.GeneratePasswordResetTokenAsync(user);
        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
        var callbackUrl = Navigation.GetUriWithQueryParameters(
            Navigation.ToAbsoluteUri(ResetPassword.PageUrl).AbsoluteUri,
            new Dictionary<string, object?> { ["userId"] = user.Id, ["token"] = code });
        await Mediator.Publish(new ResetPasswordNotification(callbackUrl, user.Email!, user.UserName!));
        Logger.LogInformation("Rest password email sent to {0}.", Input.Email);
        RedirectManager.RedirectTo(ForgotPasswordConfirmation.PageUrl);
    }


    private sealed class InputModel
    {
        [Required] [EmailAddress] public string Email { get; set; } = "";
    }

}